<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="editDialogVisible=true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="{row}">
                  <el-button size="small" type="success" @click="showPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="total"
                :page-size="query.pagesize"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="formData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 编辑功能 -->
    <el-dialog
      title="编辑"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form ref="editForm" label-width="80px" :rules="rules" :model="roleForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isCancel">取 消</el-button>
        <el-button type="primary" @click="isOk">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="permissionDialogVisible"
      width="50%"
    >
      <el-tree
        ref="permTree"
        :data="permData"
        :props="{label: 'name'}"
        :show-checkbox="true"
        :check-strictly="true"
        :default-expand-all="true"
        :default-checked-keys="selectCheck"
        node-key="id"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, deleteRole, getRoleDetail, updateRole, addRole } from '@/api/setting'
import { mapGetters } from 'vuex'
import { tranListToTreeData } from '@/utils'
import { getPermissionList, assignPerm } from '@/api/permission'
export default {
  data() {
    return {
      activeName: 'first',
      query: {
        page: 1,
        pagesize: 2
      },
      list: [],
      total: 0,
      formData: {},
      editDialogVisible: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      permissionDialogVisible: false,
      permData: [],
      roleId: null,
      selectCheck: []
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleList(this.query)
      console.log(res)
      this.total = res.total
      this.list = res.rows
    },
    handleCurrentChange(current) {
      this.query.page = current
      this.getRoleList()
    },
    async getCompanyInfo() {
      // console.log(this.$store.state.user.userInfo.companyId)
      // console.log(this.$store.getters.companyId)
      console.log(this.companyId)
      const res = await getCompanyInfo(
        this.$store.state.user.userInfo.companyId
      )
      console.log(123)
      console.log(res)
      this.formData = res
    },
    deleteRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(id)
        this.getRoleList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async editRole(id) {
      this.editDialogVisible = true
      const res = await getRoleDetail(id)
      console.log(res)
      this.roleForm = res
    },
    isCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    async isOk() {
      // 表单校验
      try {
        await this.$refs.editForm.validate()
        if (this.roleForm.id) {
          // 如果this.roleForm.id是存在的，当前做的是编辑功能
          await updateRole(this.roleForm)
        } else {
          // 新增功能
          await addRole(this.roleForm)
        }
        this.$message.success('编辑成功')
        this.getRoleList()
        this.editDialogVisible = false
      } catch (err) {
        this.$message.error('用户名不能为空')
      }
    },
    async showPermission(id) {
      this.roleId = id
      const { permIds } = await getRoleDetail(id) // permIds是当前角色所拥有的权限点数据
      console.log(permIds)
      this.selectCheck = permIds // 将当前角色所拥有的权限id赋值
      this.permData = tranListToTreeData(await getPermissionList(), '0') // 转化list到树形数据
      this.permissionDialogVisible = true
    },
    async savePermission() {
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      this.$message.success('分配权限成功')
      this.permissionDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__footer{
  display: flex;
  justify-content: center;
}
</style>

